extends KinematicBody2D

class_name EnemyBase

export var hp:int

signal die_signal
var velocity
var _is_red setget set_is_red,get_is_red
var normal_turn_range_time=[0.3,1.1]
onready var normal_turn_time=rand_range(normal_turn_range_time[0],normal_turn_range_time[1])
var normal_turn_timer=0.0

var block_turn_time=0.3
var block_turn_timer=0.0

export var speed:float
export var cd_time_range=[0.5,1.5]
onready var cd_time=rand_range(cd_time_range[0],cd_time_range[1])
onready var cd_timer=0
var attack_val=10
var bullet_speed=150
export(PackedScene) var bullet_tscn:PackedScene

func _fire():
	var bullet:Area2D= bullet_tscn.instance()
	get_tree().current_scene.add_child(bullet)
	bullet.position=$FirePos.global_position
	bullet.attack_val=attack_val
	bullet.speed=bullet_speed
	bullet.rotation=self.rotation

func get_random_degree()->int:
	var rand_num= randi()%6
	if rand_num==0:
		return 0
	elif rand_num==1:
		return 90
	elif rand_num==2:
		return 270
	else:
		return 180
		
func set_is_red(is_red):
	_is_red=is_red
	if is_red:
		$AnimatedSprite.play("RunRed")
	else:
		$AnimatedSprite.play("Run")

func _ready():
	randomize()
	self.rotation_degrees=get_random_degree()

func _physics_process(delta):
	if get_tree().current_scene.get_node("EnemysManager").pause==true: return 
	cd_timer+=delta
	if cd_timer>cd_time:
		_fire()
		cd_timer=0
		cd_time=rand_range(cd_time_range[0],cd_time_range[1])
		
	velocity=move_and_slide(Vector2.UP.rotated(self.rotation)*speed,Vector2.ZERO,false,1,0,false)
	if velocity.length()<1:
		block_turn_timer+=delta
		if block_turn_timer>block_turn_time:
			block_turn_timer=0
			rand_rotate_tank();
	else:
		normal_turn_timer+=delta
		if normal_turn_timer>normal_turn_time:
			normal_turn_timer=0
			rand_rotate_tank()
			normal_turn_time=rand_range(normal_turn_range_time[0],normal_turn_range_time[1])

func rand_rotate_tank():
	self.rotation_degrees=get_random_degree()
	if rotation_degrees==90 or self.rotation_degrees==270:
		self.global_position.y=round(self.global_position.y/16)*16
	else:
		self.global_position.x=round(self.global_position.x/16)*16

func get_is_red():
	return _is_red

func take_damage(_attack_val,_bullet_dir):
	if _is_red:
		get_tree().current_scene.add_prop()
		set_is_red(false)
	hp-=_attack_val
	if hp<=0:
		die()

func die():
	emit_signal("die_signal")
	yield(get_tree(),"idle_frame")
	queue_free()
